package com.cmdi.opensite.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cmdi.opensite.config.JwtAuthenticationFilter;
import com.cmdi.opensite.entity.User;
import com.cmdi.opensite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        boolean success = userService.register(user);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "注册成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "用户名或邮箱已存在");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        User user = userService.login(username, password);
        if (user != null) {
            // 生成JWT token
            String token = jwtAuthenticationFilter.generateToken(user.getId());
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("token", token);
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("nickname", user.getNickname());
            userMap.put("avatar", user.getAvatar());
            result.put("user", userMap);
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "用户名或密码错误");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestAttribute("userId") Long userId) {
        User user = userService.getById(userId);
        if (user != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("id", user.getId());
            result.put("username", user.getUsername());
            result.put("nickname", user.getNickname());
            result.put("email", user.getEmail());
            result.put("phone", user.getPhone());
            result.put("avatar", user.getAvatar());
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.notFound().build();
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(@RequestBody User user, @RequestAttribute("userId") Long userId) {
        user.setId(userId);
        boolean success = userService.updateUserInfo(user);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "更新成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "更新失败");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public ResponseEntity<?> changePassword(@RequestBody Map<String, String> passwordData, @RequestAttribute("userId") Long userId) {
        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "密码修改成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "原密码错误");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 分页查询用户列表（管理员接口）
     */
    @GetMapping("/page")
    public ResponseEntity<?> getUserPage(@RequestParam(defaultValue = "1") Integer current, 
                                        @RequestParam(defaultValue = "10") Integer size,
                                        @RequestParam(required = false) String keyword) {
        IPage<User> page = userService.selectUserPage(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size), keyword);
        return ResponseEntity.ok(page);
    }
}